#%%
from datetime import datetime
import os
from pathlib import Path
import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd







#%%
######################## 输入路径 ###############################################

input_file = r'./data/BICS5-SLC_PE_DR-CT.dat'

#################################################################################








#%%
######################## 创建输出文件夹 ###############################################
def make_output_dirs(file_path):
    # 获取文件名（包括扩展名）
    file_name = os.path.basename(file_path)
    # 去除扩展名，得到文件名
    filename_without_extension = os.path.splitext(file_name)[0]
    # 构建输出文件夹路径
    step0_output_folder = os.path.join(os.path.dirname(file_path), 'output', filename_without_extension, '0_temp')
    step1_output_folder = os.path.join(os.path.dirname(file_path), 'output', filename_without_extension, '1_result')
    
    # 创建输出文件夹
    os.makedirs(step0_output_folder, exist_ok=True)
    os.makedirs(step1_output_folder, exist_ok=True)

    # 返回输出文件夹路径
    return step0_output_folder, step1_output_folder, filename_without_extension

step0_output_folder, step1_output_folder, filename_without_extension = make_output_dirs(input_file)
output_file_path = os.path.join(step1_output_folder, "result_" + filename_without_extension + ".xlsx")
#################################################################################


#%%
######################## 清空文件夹 ###############################################
def clear_folder(folder_path):
    # 检查文件夹是否存在
    if not os.path.exists(folder_path):
        print(f"文件夹 {folder_path} 不存在，无需清空")
        return

    # # 提示用户是否确定清空
    # choice = input(f"确定要清空文件夹 {folder_path} 吗？(Y/N): ")
    # if choice.lower() != 'y':
    #     print("取消清空")
    #     return

    # 清空文件夹
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            os.remove(file_path)
        for dir in dirs:
            dir_path = os.path.join(root, dir)
            os.rmdir(dir_path)

    print(f"文件夹 {folder_path} 已清空")

clear_folder(step0_output_folder)
clear_folder(step1_output_folder)
#################################################################################



#%%
######################## step0：分割文件 ###############################################
def process_dat_file(input_file, output_path):
    prefix_counter = 1  # 初始化前缀计数器为 1
    current_flag = None  # 初始化当前标志为空
    current_file = None  # 初始化当前文件对象为空

    with open(input_file, 'r') as file:  # 打开文件
        for line in file:  # 逐行读取文件内容
            if ']' in line and '<' in line:  # 检查行中是否包含标志
                start_index = line.index(']') + 1  # 获取标志起始位置
                end_index = line.index('<')  # 获取标志结束位置
                flag = line[start_index:end_index].strip()  # 提取标志内容并去除空格

                if flag != current_flag:  # 如果标志与当前标志不同
                    if current_file:  # 如果当前文件对象存在，则关闭文件
                        current_file.close()

                    current_flag = flag  # 更新当前标志
                    file_name = f"{prefix_counter}-{current_flag}.txt"  # 构造文件名
                    file_path = os.path.join(output_path, file_name)
                    current_file = open(file_path, 'a')  # 打开文件以追加模式写入内容
                    prefix_counter += 1  # 前缀计数器加一

                current_file.write(line)  # 将行内容写入当前文件

    if current_file:  # 如果当前文件对象存在，则关闭文件
        current_file.close()

process_dat_file(input_file, step0_output_folder)
#################################################################################










#%%
######################## step1: 处理 ###############################################
def calculate_time_difference(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        
        if len(lines) < 2:
            return datetime.strptime(lines[0][2:17], '%Y%m%d-%H%M%S') - datetime.strptime(lines[0][2:17], '%Y%m%d-%H%M%S')
        
        first_line = lines[0]
        last_line = lines[-1]
        

        first_timestamp = datetime.strptime(first_line[2:17], '%Y%m%d-%H%M%S')
        last_timestamp = datetime.strptime(last_line[2:17], '%Y%m%d-%H%M%S')
        time_difference = last_timestamp - first_timestamp
        return time_difference


def count_lines(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        return len(lines)

def blocks_and_cycles(file_path):
    block_set = set()
    cycle_set = set()

    with open(file_path, 'r') as file:
        for line in file:
            # 从每行中提取block和cycle
            if '<block>' in line:
                block = line.split('<block>')[1].split()[0]
                block_set.add(block)
            if '<cycle>' in line:
                cycle = line.split('<cycle>')[1].split()[0]
                cycle_set.add(cycle)

    return block_set, cycle_set



# 直接计算总时间
total_time_diff = calculate_time_difference(input_file).total_seconds()
total_time_in_hour = round(total_time_diff / 3600, 4)
print("总时间：", total_time_diff, "s")
print("总时间：", total_time_in_hour, "h")





result = {}
folder_path = step0_output_folder
# 获取文件夹下所有文件
files = os.listdir(folder_path)
# 按数字递增的方式排序文件
sorted_files = sorted(files, key=lambda x: int(x.split('-')[0]))


for file in sorted_files:
    # 分割文件名为前缀和文件名部分
    prefix, filename = file.split('-', 1)
    filename_without_extension = filename.split(".")[0]
    # 构建文件的完整路径
    file_path = os.path.join(folder_path, file)
    
    # 调用处理函数处理文件
    time_difference = calculate_time_difference(file_path)
    time_difference_seconds = time_difference.total_seconds()
    line_count = count_lines(file_path)
    if line_count <= 1:
        single_line_time_difference = 0
    else:
        single_line_time_difference = time_difference_seconds / (line_count - 1)

    my_key = Path(file_path).stem
    my_value = {"prefix": int(prefix), "filename_without_extension": filename_without_extension,"time_difference_seconds": time_difference_seconds, "line_count": line_count, "single_line_time_difference": single_line_time_difference}

    result[my_key] = my_value
#################################################################################







#%%
######################## 保存至excel ###############################################


# 创建一个新的Excel文件
wb = openpyxl.Workbook()
# 选择默认的活动工作表
ws = wb.active

# 写入表头
ws['A1'] = '编号'
ws['B1'] = '名称'
ws['C1'] = '时间差值(s)'
ws['D1'] = '行数(s)'
ws['E1'] = '单行时间差值(s)'

row = 2
total_time_diff = 0

for key in result:
    ws.cell(row=row, column=1, value=result[key]["prefix"])
    ws.cell(row=row, column=2, value=result[key]["filename_without_extension"])
    ws.cell(row=row, column=3, value=round(result[key]["time_difference_seconds"], 4))
    ws.cell(row=row, column=4, value=result[key]["line_count"])
    ws.cell(row=row, column=5, value=round(result[key]["single_line_time_difference"], 4))
    total_time_diff += result[key]["time_difference_seconds"]
    row += 1

# 将数据加载到pandas的DataFrame中
df = pd.DataFrame(ws.values)[1:]
# 按照第二列的名称排序，再按照第一列的数字排序
df_sorted = df.sort_values(by=[1, 0])

# 清空Excel工作表中的数据（除了表头）
ws.delete_rows(2, ws.max_row)

# 将排序后的数据写回Excel文件
for r in dataframe_to_rows(df_sorted, index=False, header=False):
    ws.append(r)

# 写入总和和单位换算
ws.cell(row=row, column=2, value='总和(s)')
ws.cell(row=row, column=3, value=round(total_time_diff,4))

# 将总和的单位换算成h
ws.cell(row=row+1, column=2, value='总和(h)')
ws.cell(row=row+1, column=3, value=round(total_time_diff/3600, 4))


# 调整列宽
ws.column_dimensions['A'].width = 5
ws.column_dimensions['B'].width = 20
ws.column_dimensions['C'].width = 15
ws.column_dimensions['D'].width = 10
ws.column_dimensions['E'].width = 15
ws.column_dimensions['F'].width = 15

# 冻结第一行
ws.freeze_panes = "A2"
# 添加筛选
ws.auto_filter.ref = ws.dimensions


# 保存Excel文件
wb.save(output_file_path)

#################################################################################


